var locationHelper = require('../../../utils/location_helper.js');

function getLocation(callBack){
  checkLocaltionPerssion(function(){
    //success
    checkLocation(function(data){
      callBack(data)
    })
  },function(){
    //fail
    callBack(null)
  })
}
function checkLocaltionPerssion(_success,_fail){
  wx.getSetting({
    success: (res) => {
      if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
        wx.showModal({
          title: '是否授权当前位置',
          content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
          success: function (res) {
            if (res.cancel) {
              wx.showToast({
                title: '授权失败',
                duration: 1000
              })
              _fail()
            } else if (res.confirm) {
              wx.openSetting({
                success: function (dataAu) {
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    //再次授权，调用getLocationt的API
                    _success()
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'success',
                      duration: 1000
                    })
                    _fail()
                  }
                }
              })
            }
          }
        })
      } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
        _success()
      }
      else { //授权后默认加载
        _success()
      }
    }
  })
}
function checkLocation(callBack){
  console.log("start getLocation...")
  wx.getLocation({
    type: 'wgs84',
    success: function (res) {
      locationHelper.getReverseGeocoder(res.latitude, res.longitude, function (addressRes) {
        console.log(addressRes)
        var mCity = addressRes.result.address_component.city
        var mAddress = addressRes.result.address;
        var mLat = addressRes.result.location.lat;
        var mLng = addressRes.result.location.lng;
        var obj = {
          lat: mLat,
          lng: mLng,
          address: mAddress,
          city: mCity
        }
        callBack(obj)
      })
    },
  })
}
module.exports = {
  getLocation: getLocation,
  checkLocaltionPerssion: checkLocaltionPerssion
}